/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.admin.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.IOUtils;
import com.pig4cloud.pig.admin.api.entity.SysFile;
import com.pig4cloud.pig.admin.mapper.SysFileMapper;
import com.pig4cloud.pig.admin.service.SysFileService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.minio.service.MinioTemplate;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.minio.ObjectStat;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件管理
 *
 * @author Luckly
 * @date 2019-06-18 17:18:42
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {

	private final MinioTemplate minioTemplate;

	@Value("${open-bucket:admaterial}")
	private String openBucket;

	@Value("${base-http-url:http://localhost:8821}")
	private String baseHttpUrl;

	private static final Map<String, String> CONTENT_TYPE_MAPPING = new HashMap<String, String>() {{
		put("jpeg", MediaType.IMAGE_JPEG_VALUE);
		put("jpg", MediaType.IMAGE_JPEG_VALUE);
		put("png", MediaType.IMAGE_PNG_VALUE);
		put("gif", MediaType.IMAGE_GIF_VALUE);
		put("mp3", "audio/mp3");
		put("mp4", "video/mp4");
		put("mpeg4", "video/mpeg4");
		put("avi", "video/avi");
		put("wmv", "video/x-ms-wmv");
	}};


	/**
	 * 上传文件
	 *
	 * @param file
	 * @return
	 */
	@Override
	public R uploadFile(MultipartFile file) {
		String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		Map<String, String> resultMap = new HashMap<>(4);
		resultMap.put("bucketName", CommonConstants.BUCKET_NAME);
		resultMap.put("fileName", fileName);

		try {
			minioTemplate.putObject(CommonConstants.BUCKET_NAME, fileName, file.getInputStream());
			//文件管理数据记录,收集管理追踪文件
			fileLog(file, fileName);
		} catch (Exception e) {
			log.error("上传失败", e);
			return R.failed(e.getLocalizedMessage());
		}
		return R.ok(resultMap);
	}

	/**
	 * 读取文件
	 *
	 * @param fileName
	 * @param response
	 */
	@Override
	public void getFile(String fileName, HttpServletResponse response) {
		int separator = fileName.lastIndexOf(StrUtil.DASHED);
		try (InputStream inputStream = minioTemplate.getObject(fileName.substring(0, separator),
				fileName.substring(separator + 1))) {
			response.setContentType("application/octet-stream; charset=UTF-8");
			IoUtil.copy(inputStream, response.getOutputStream());
		} catch (Exception e) {
			log.error("文件读取异常", e);
		}
	}


	/**
	 * 删除文件
	 *
	 * @param id
	 * @return
	 */
	@Override
	@SneakyThrows
	@Transactional(rollbackFor = Exception.class)
	public Boolean deleteFile(Long id) {
		SysFile file = this.getById(id);
		minioTemplate.removeObject(CommonConstants.BUCKET_NAME, file.getFileName());
		return this.removeById(id);
	}

	/**
	 * 通用上传文件
	 *
	 * @param bucketName
	 * @param file
	 * @return
	 */
	@Override
	public R uploadFile(String bucketName, MultipartFile file) throws IOException {
		String fileName = DigestUtil.md5Hex(file.getBytes()) + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		try {
			minioTemplate.putObject(bucketName, fileName, file.getInputStream());
			//文件管理数据记录,收集管理追踪文件
			fileLog(file, fileName);
		} catch (Exception e) {
			log.error("上传失败", e);
			return R.failed(e.getLocalizedMessage());
		}
		return R.ok(Collections.singletonMap("fileUrl", String.format("%s/admin/sys-file/readFile/%s/%s", baseHttpUrl, bucketName, fileName)));
	}

	/**
	 * 文件管理数据记录,收集管理追踪文件
	 *
	 * @param file     上传文件格式
	 * @param fileName 文件名
	 */
	private void fileLog(MultipartFile file, String fileName) {
		SysFile sysFile = new SysFile();
		//原文件名
		String original = file.getOriginalFilename();
		sysFile.setFileName(fileName);
		sysFile.setOriginal(original.length() > 90 ? original.substring(0, 90) : original);
		sysFile.setFileSize(file.getSize());
		sysFile.setType(FileUtil.extName(original));
		sysFile.setBucketName(CommonConstants.BUCKET_NAME);
		sysFile.setCreateUser(SecurityUtils.getUser().getUsername());
		this.save(sysFile);
	}


	/**
	 * 读取文件
	 *
	 * @param bucketName
	 * @param objectName
	 * @param response
	 */
	@SneakyThrows
	@Override
	public void readFile(String bucketName, String objectName, HttpServletResponse response) {
		if (!openBucket.equals(bucketName) && !openBucket.contains(bucketName)) {
			response.setContentType(MediaType.APPLICATION_JSON_VALUE);
			response.getOutputStream().println(String.format("{\"code\",\"1\", \"msg\": \"unknown bucket '%s'\"}", bucketName));
			return;
		}
		InputStream is = minioTemplate.getObject(bucketName, objectName);
		ObjectStat objectInfo = minioTemplate.getObjectInfo(bucketName, objectName);
		long objectLen = objectInfo.length();

		int idx = objectName.lastIndexOf(".");
		String fileType = objectName.substring(idx + 1);
		response.setContentType(CONTENT_TYPE_MAPPING.getOrDefault(fileType, MediaType.APPLICATION_OCTET_STREAM_VALUE));
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName, StandardCharsets.UTF_8.displayName()));
		response.addHeader("Content-Length", String.valueOf(objectLen));
		IOUtils.copy(is, response.getOutputStream());
	}

}
